package com.atguigu.grainmall.order.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author shiyuan
 * @Date 2023/3/30 9:35
 * @Version 1.0
 * sentinel 自定义返回数据配置
 **/
@Configuration
public class GrainmallSentinelConfig {

    // 构造器 构造是直接传递
    public GrainmallSentinelConfig() {
        // 如果请求被限制(阻塞)了 处理器处理
        WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
            @Override
            public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException, IOException {
                // 返回被阻塞数据消息
                R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMsg());
                // 响应传回数据字符集编码格式
                response.setCharacterEncoding("UTF-8");
                // 响应传回数据类型
                response.setContentType("application/json");
                // 返回错误提示
                response.getWriter().write(JSON.toJSONString(error));
            }
        });

    }

}
